package com.yxd.demo.rule;

import com.yxd.demo.domain.Coupon;
import com.yxd.demo.domain.Product;
import org.jeasy.rules.annotation.Action;
import org.jeasy.rules.annotation.Condition;
import org.jeasy.rules.annotation.Rule;
import org.jeasy.rules.api.Facts;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @author: yxd
 * @date: 2022/8/8 10:56
 */
@Component(value = "productRule")
@Rule(name = "商品规则", description = "判断商品是否在优惠券范围内", priority = 20)
public class ProductRule {
    @Condition
    public boolean condition(Facts facts) {
        List<Coupon> couponList = facts.get("couponList");
        return !CollectionUtils.isEmpty(couponList);
    }

    @Action
    public void action(Facts facts){
        List<Coupon> usableCouponList = new ArrayList<>();
        Product product = facts.get("product");
        List<Coupon> couponList = facts.get("couponList");
        Long productId = product.getProductId();
        for (Coupon coupon : couponList){
            Integer limit = coupon.getLimit();
            if (Objects.equals(2, limit)){
                usableCouponList.add(coupon);
                continue;
            }
            List<Long> productIdList = coupon.getProductIdList();
            if (!productIdList.contains(productId)){
                continue;
            }
            usableCouponList.add(coupon);
        }
        facts.put("couponList", usableCouponList);
    }
}
